package com.bzgwl.mybatis_plus.config;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bzgwl.mybatis_plus.annotatin.PkEnum;
import com.bzgwl.mybatis_plus.annotatin.PkHasPermissions;
import com.bzgwl.mybatis_plus.sys.entity.Permission;
import com.bzgwl.mybatis_plus.sys.entity.User;
import com.bzgwl.mybatis_plus.sys.mapper.PermissionMapper;
import com.bzgwl.mybatis_plus.sys.mapper.UserMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Aspect
@SuppressWarnings("all")
public class AopConfig {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserMapper userMapper;

    @Before(value="@annotation(com.bzgwl.mybatis_plus.annotatin.PkHasPermissions)")
    public void dofore(JoinPoint jp) throws Exception {

        //通过获取PkHasPermissions注解
        Method proxyMethod = ((MethodSignature) jp.getSignature()).getMethod();
        Method targetMethod = jp.getTarget().getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes());
        PkHasPermissions pkHasPermissions = targetMethod.getAnnotation(PkHasPermissions.class);

        //处理注解逻辑
        String[] pers = pkHasPermissions.value();
        PkEnum pkLogical = pkHasPermissions.pkLogical();

        if(pers ==null){
            return;
        }

        //获取当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails user = (UserDetails) authentication.getPrincipal();

        Wrapper wrapper = new QueryWrapper();
        ((QueryWrapper) wrapper).eq("username",user.getUsername());
        User myUser = userMapper.selectOne(wrapper);

        List<Permission> list = permissionMapper.findUserPermission(myUser.getId());
        if(pers.length == 1){
            for(Permission p : list){
                if(p.getAuth().trim().equals(pers[0].trim())){
                    return;
                }
            }
        }
        if(pers.length > 1){
            Set<String> havePer = new HashSet();
            Set<String> needPer = new HashSet();

            list.forEach(p ->{
                havePer.add(p.getAuth().trim());
            });
            for(String s : pers){
                needPer.add(s.trim());
            }

            if(pkLogical == PkEnum.AND){
                boolean b = havePer.containsAll(needPer);
                if(b){
                    return;
                }
            }
            if(pkLogical == PkEnum.OR){
                havePer.retainAll(needPer); //交集
                if(havePer.size()>0){
                    return;
                }
            }

        }

        throw new AccessDeniedException("没有权限访问");

        //获取Request对象
        //ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //HttpServletRequest request = attributes.getRequest();
        //request.setAttribute("tip", tip);
    }
}
